import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export const useMachineStore = defineStore('machine', {
  state: () => ({
    machines: [] as any[],
    statistics: {
      typeDistribution: [],
      statusDistribution: [],
      usageFrequency: [],
      failureRate: [],
    },
    filters: {
      startDate: '',
      endDate: '',
      ownerId: '',
      machineCategory: '',
      machineName: '',
      machineNumber: '',
      page: 1,
      size: 10,
    },
  }),
  actions: {
    async fetchStatistics() {
      try {
        const response = await axios.get('/machine/stats', { params: this.filters });
        if (response.data.code === 200) {
          this.statistics = response.data.data;
          return response;
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error('获取统计数据失败');
        throw error;
      }
    },
    async fetchMachines() {
      try {
        const response = await axios.post('/machine/list', this.filters);
        if (response.data.code === 200) {
          // 提取 content 字段作为 machines
          this.machines = response.data.data.content || [];
          // 返回整个 response 以便获取分页信息
          return response;
        } else {
          ElMessage.error(response.data.message);
          return null;
        }
      } catch (error) {
        ElMessage.error('获取机器列表失败');
        throw error;
      }
    },
    async addMachine(machine: any) {
      try {
        const response = await axios.post('/machine/add', machine);
        if (response.data.code === 200) {
          this.machines.push(response.data.data);
          ElMessage.success('添加成功');
          return response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error('添加失败');
        throw error;
      }
    },
    async updateMachine(machine: any) {
      try {
        const response = await axios.put('/machine/update', machine);
        if (response.data.code === 200) {
          const index = this.machines.findIndex((m) => m.id === machine.id);
          if (index !== -1) {
            this.machines[index] = response.data.data;
          }
          ElMessage.success('更新成功');
          return response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error('更新失败');
        throw error;
      }
    },
    async deleteMachine(id: number) {
      try {
        const response = await axios.delete(`/machine/delete/${id}`);
        if (response.data.code === 200) {
          this.machines = this.machines.filter((m) => m.id !== id);
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error('删除失败');
        throw error;
      }
    },
    setFilters(filters: Partial<typeof this.filters>) {
      this.filters = { ...this.filters, ...filters };
    },
    clearFilters() {
      this.filters = {
        startDate: '',
        endDate: '',
        ownerId: '',
        machineCategory: '',
        machineName: '',
        machineNumber: '',
        page: 1,
        size: 10,
      };
    },
  },
});